class ZenMirrorGenerator:
    """禅镜数字人模型工具类"""

    def __init__(self, config: ExtendedAIConfig):
        self.config = config
        self.zen_config = config.configs["zenmirror"]

    def create_digital_human(self,
                             script: str,
                             avatar_id: str = "default",
                             voice_config: Optional[Dict] = None,
                             video_config: Optional[Dict] = None,
                             **kwargs) -> Dict[str, Any]:
        """使用禅镜创建数字人视频"""

        # 合并配置参数
        base_config = self.config.zenmirror_defaults.copy()
        if video_config:
            base_config.update(video_config)
        base_config.update(kwargs)

        # 构建语音配置
        voice_settings = {
            "voice_id": "zh-CN-XiaoxiaoNeural",
            "speed": 1.0,
            "pitch": 1.0,
            "volume": 1.0
        }
        if voice_config:
            voice_settings.update(voice_config)

        payload = {
            "model": "zenmirror-v1",
            "script": script,
            "avatar_id": avatar_id,
            "voice_settings": voice_settings,
            "video_settings": {
                "resolution": base_config["resolution"],
                "frame_rate": base_config["frame_rate"],
                "output_format": base_config["output_format"],
                "background": base_config["background"]
            },
            "animation_settings": {
                "emotion_intensity": base_config["emotion_intensity"],
                "head_movement": base_config["head_movement_range"],
                "lip_sync": base_config["lip_sync_accuracy"]
            }
        }

        try:
            response = requests.post(
                f"{self.zen_config['base_url']}/generate",
                headers={
                    "Authorization": f"Bearer {self.zen_config['api_key']}",
                    "Content-Type": "application/json"
                },
                json=payload,
                timeout=300
            )

            if response.status_code == 200:
                result = response.json()
                return {
                    "success": True,
                    "task_id": result.get("task_id"),
                    "status": "processing",
                    "estimated_time": result.get("estimated_time", 60),
                    "provider": "zenmirror"
                }
            else:
                return {
                    "success": False,
                    "error": f"禅镜生成失败: {response.text}",
                    "status_code": response.status_code,
                    "provider": "zenmirror"
                }

        except requests.exceptions.Timeout:
            return {
                "success": False,
                "error": "请求超时，请稍后重试",
                "provider": "zenmirror"
            }
        except Exception as e:
            return {
                "success": False,
                "error": f"请求异常: {str(e)}",
                "provider": "zenmirror"
            }

    def create_with_audio(self,
                          audio_file_path: str,
                          avatar_id: str = "default",
                          **kwargs) -> Dict[str, Any]:
        """使用音频文件创建数字人视频"""

        if not os.path.exists(audio_file_path):
            return {
                "success": False,
                "error": "音频文件不存在",
                "provider": "zenmirror"
            }

        try:
            with open(audio_file_path, 'rb') as audio_file:
                files = {
                    'audio': audio_file,
                    'config': (None, json.dumps({
                        "avatar_id": avatar_id,
                        "model": "zenmirror-v1",
                        **kwargs
                    }), 'application/json')
                }

                response = requests.post(
                    f"{self.zen_config['base_url']}/generate_with_audio",
                    headers={
                        "Authorization": f"Bearer {self.zen_config['api_key']}"
                    },
                    files=files,
                    timeout=300
                )

                if response.status_code == 200:
                    result = response.json()
                    return {
                        "success": True,
                        "task_id": result.get("task_id"),
                        "status": "processing",
                        "provider": "zenmirror"
                    }
                else:
                    return {
                        "success": False,
                        "error": f"音频生成失败: {response.text}",
                        "provider": "zenmirror"
                    }

        except Exception as e:
            return {
                "success": False,
                "error": f"请求异常: {str(e)}",
                "provider": "zenmirror"
            }

    def get_avatar_list(self) -> List[Dict]:
        """获取可用的数字人形象列表"""
        try:
            response = requests.get(
                f"{self.zen_config['base_url']}/avatars",
                headers={
                    "Authorization": f"Bearer {self.zen_config['api_key']}"
                },
                timeout=30
            )

            if response.status_code == 200:
                return response.json().get("avatars", [])
            else:
                print(f"获取形象列表失败: {response.text}")
                return []

        except Exception as e:
            print(f"获取形象列表异常: {str(e)}")
            return []

    def check_task_status(self, task_id: str) -> Dict[str, Any]:
        """检查任务状态"""
        try:
            response = requests.get(
                f"{self.zen_config['base_url']}/tasks/{task_id}",
                headers={
                    "Authorization": f"Bearer {self.zen_config['api_key']}"
                },
                timeout=30
            )

            if response.status_code == 200:
                task_data = response.json()
                status = task_data.get("status")
                result = {
                    "success": True,
                    "status": status,
                    "progress": task_data.get("progress", 0),
                    "provider": "zenmirror"
                }

                if status == "completed":
                    result["video_url"] = task_data.get("video_url")
                    result["duration"] = task_data.get("duration")
                    result["file_size"] = task_data.get("file_size")
                elif status == "failed":
                    result["error"] = task_data.get("error_message", "未知错误")

                return result
            else:
                return {
                    "success": False,
                    "error": f"状态查询失败: {response.text}",
                    "provider": "zenmirror"
                }

        except Exception as e:
            return {
                "success": False,
                "error": f"查询异常: {str(e)}",
                "provider": "zenmirror"
            }